use crate::entity::sys_org::SysOrg;
use crate::entity::{fetch_page, PaginationOptions};
use crate::service::DATE_FORMAT;
use crate::vo::sys_org_vo::{AddSysOrgReq, OrgPageReq};
use crate::SQLX;
use chrono::Local;
use salvo::{Depot, Request};
use sqlx::sqlite::SqliteQueryResult;

pub struct OrgService {}

impl OrgService {
    pub async fn add_org(
        request: &mut Request,
        depot: &mut Depot,
    ) -> anyhow::Result<()> {
        let db = SQLX.get().ok_or(anyhow::anyhow!("db error"))?;
        let org_req = request.parse_json::<AddSysOrgReq>().await?;
        let org = SysOrg {
            org_id: None,
            org_name: org_req.org_name,
            create_time: Some(Local::now().format(DATE_FORMAT).to_string()),
            remark: None,
        };
        org.add_org().await?;
        Ok(())
    }
    pub async fn org_page(
        request: &mut Request,
        depot: &mut Depot,
    ) -> anyhow::Result<crate::entity::Page<SysOrg>> {
        let page_req = request.parse_json::<OrgPageReq>().await?;
        let paginate = PaginationOptions {
            page_no: page_req.page_no,
            page_size: page_req.page_size,
        };
        let pages = fetch_page::<SysOrg>("select * from sys_org", &paginate).await?;
        Ok(pages)
    }
}
